package labs.utilities;

import static labs.utilities.PrintUtilities.printInfo;
import static labs.utilities.PrintUtilities.printError;
import static labs.utilities.PrintUtilities.printException;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class LabsFileReader extends LabsFileIO {
	private BufferedReader reader;

	public LabsFileReader(String fileName) {
		super(fileName, true);
	}

	public LabsFileReader(String fileName, boolean openOnCreation) {
		super(fileName, openOnCreation);
	}

	public void open() {
		try {
			reader = new BufferedReader(new FileReader(getFileName()));
			setClosable(reader);
			setOpened(true);
		} catch (Exception ex) {
			printError("Couldn't open file: %s", getFileName());
			printException(ex);
		}
	}

	public String[] readLines(boolean keepNewLineChar) {
		ArrayList<String> lines = new ArrayList<String>(10);
		String line = "";
		while ((line = readLine(keepNewLineChar)) != null) {
			lines.add(line);
		}
		return lines.toArray(new String[lines.size()]);
	}

	public String[] readLines() {
		return readLines(false);
	}

	private String readLine(boolean keepNewLineChar) {
		try {
			String line = reader.readLine();
			if (line != null) {
				return line + (keepNewLineChar ? "\n" : "");
			}
		} catch (Exception ex) {
			printError("Couldn't Read Line");
			printException(ex);
		}
		return null;
	}

	public BufferedReader getStreamReader() {
		return reader;
	}

	public void reset() {
		try {
			if (reader.markSupported()) {
				reader.reset();
				return;
			}
		} catch (IOException e) {
			//printError("Couldn't Reset reader using predefined method");
			//printException(e);
		} finally {
			//printInfo("Attempt to close and reopen the file");
			close();
			open();
		}

	}
}
